/*************************************************************
 * File: PassportResource.java
 * Copyright (c) 2012
 * Author: Huang Shaobin
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Feb 11, 2013
 * Description: 
 ************************************************************/

package snow.biz.system.web.resource;

import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;

import snow.biz.system.model.Group;
import snow.biz.system.model.User;
import snow.biz.system.service.IGroupService;
import snow.biz.system.service.IUserService;
import snow.biz.system.web.SystemWebConstants;
import snow.core.context.AccessContext;
import snow.core.exception.BusinessException;
import snow.core.security.Operation;
import snow.core.security.OperationType;
import snow.core.security.Resource;
import snow.core.toolkit.Validator;
import snow.core.toolkit.security.Cryptogram;
import snow.core.web.restlet.ResourceSupport;

/**
 * 系统登录资源
 * 
 * @author Shaobin.Software@gmail.com Shaobin_Software@163.com
 * @version 1.0
 */
@Path(SystemWebConstants.PATH_PASSPORT)
@Resource(uri = SystemWebConstants.RESOURCE_PASSPORT, needCheck = false, name = "通行资源", desc = "通行资源，即用户录入、登出功能")
public class PassportResource extends ResourceSupport {

	private IGroupService groupService;
	private IUserService userService;

	/**
	 * 退出登录
	 * 
	 * @return
	 */
	@DELETE
	@Operation(OperationType.REMOVE)
	@Produces(MediaType.APPLICATION_JSON)
	public Object cancelPassport() {
		try {
			log.debug("开始执行退出操作……");
			super.getSession().removeAttribute(SystemWebConstants.CURRENT_USER_ID);
			return getSuccessResult();
		} finally {
			log.debug("结束执行退出操作！");
		}
	}

	/**
	 * 校验验证码
	 * 
	 * @param validCode
	 * @throws BusinessException
	 */
	protected void checkValidCode(String validCode) throws BusinessException {
		Validator.hasText(validCode, "200001", "failure.input.not.blank");
		final AccessContext context = AccessContext.get();
		final String sessionValidCode = context.get("session_valid_code", String.class);
		Validator.hasText(sessionValidCode, "200201", "failure.system.passport.retrieved.valid.code");
		Validator.isTrue(StringUtils.endsWithIgnoreCase(sessionValidCode, validCode), "200202", "failure.system.passport.incorrect.valid.code");
	}

	public IGroupService getGroupService() {
		return this.groupService;
	}

	public IUserService getUserService() {
		return this.userService;
	}

	/**
	 * 系统登录
	 * 
	 * @param groupCode
	 * @param loginName
	 * @param loginPass
	 * @param validCode
	 * @return
	 */
	@GET
	@Operation(OperationType.SEARCH)
	@Produces(MediaType.APPLICATION_JSON)
	public Object obtainPassport(@QueryParam("groupCode")
	@DefaultValue("")
	String groupCode, @QueryParam("loginName")
	@DefaultValue("")
	String loginName, @QueryParam("loginPass")
	@DefaultValue("")
	String loginPass, @QueryParam("validCode")
	@DefaultValue("")
	String validCode) {
		try {
			log.debug("开始执行登录操作……");
			if (log.isInfoEnabled()) {
				log.info("用户登录名称为：" + loginName);
				log.info("用户登录密码为：" + loginPass);
				log.info("用户登录验证码为：" + validCode);
			}
			checkValidCode(validCode); // 校验验证码
			final Group group = groupService.searchGroupFrom(groupCode);
			Validator.notNull(group, "200205", "failure.system.passport.group.not.found");
			final User user = userService.searchUserFrom(group, loginName);
			Validator.notNull(user, "200203", "failure.system.passport.login.name.not.exist");
			Validator.isTrue(StringUtils.equalsIgnoreCase(Cryptogram.encodeByMD5(loginPass), user.getLoginPass()), "200204",
					"failure.system.passport.incorrect.login.pass");
			super.getSession().setAttribute(SystemWebConstants.CURRENT_USER_ID, user.getId()); // 写入用户ID
			return getSuccessResult();
		} catch (BusinessException e) {
			return e;
		} finally {
			log.debug("结束执行登录操作！");
		}
	}

	public void setGroupService(IGroupService groupService) {
		this.groupService = groupService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

}
